有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java计算字符串正则表达式中的字母

我有一个正则表达式,它是计算所有具有奇数X的字符串的一半

^[^X]*X(X{2}|[^X])*$

这几乎适用于所有情况:

X
XXX
XAA
AXXX
AAAX etc

但在键入以下内容时失败:

XAXAXA

我需要一个额外的子句,允许字符串具有交替的X,即XAXA。连续的X模式已被X{2}*映射


共 (3) 个答案

  1. # 1 楼答案

    试试这个,对我来说很好 ^[^X]*((X[^X]*){2})*X[^X]*$

    经受考验

    X - match
    XXX - match
    XAA - match
    AXXX - match
    AAAX - match
    XAXAXA - match
    XXAAAAAX - match
    AAXX - NO match
    AAXXXXXXAX - match
    
  2. # 2 楼答案

    非正则表达式示例

    这可能会影响性能,但我不确定您是否担心这一点

    String str = "AXXXAXAXXX";
    char[] cArray = str.toCharArray();
    int count = 0;
    
    for (char c : cArray)
    {
        if (c == 'X')
            count++;
    }
    
    if (count % 2 != 0)
        //Odd
    
  3. # 3 楼答案

    以下正则表达式匹配由不均匀数目的X组成的字符串:

    ^[^X]*(X[^X]*X[^X]*)*X[^X]*$
    

    快速细分:

    ^          # the start of the input
    [^X]*      # zero or more chars other than 'X'
    (          # start group 1
      X[^X]*   #   an 'X' followed by zero or more chars other than 'X'
      X[^X]*   #   an 'X' followed by zero or more chars other than 'X'
    )          # end  group 1
    *          # repeat group 1 zero or more times
    X          # an 'X'
    [^X]*      # zero or more chars other than 'X'
    $          # the end of the input
    

    因此,重复的组1导致匹配零或偶数个要匹配的X,而is之后的单个X使其不均匀